<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
} from '@element-plus/icons-vue'
import {ref, onMounted, computed} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox} from "element-plus";

// 1. 基础响应式变量定义（保持不变）
let searchTime = ref(["", ""])
let queryParams = ref({})
let userList = ref([])
let isSelectRow = ref(false)
let isAdd = ref(false); // 控制新增/编辑状态：true=新增，false=编辑
const tableRef = ref(null);
const selectedRows = ref([]);
const editFormRef = ref(null); // 表单实例，用于清除校验
const queryFormRef = ref(null);
const userListLoading = ref(false);

// 2. 重置查询表单（保持不变）
let resetQueryForm = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    phone: '',
    type: '',
    userRoleId: undefined,
    start: '',
    end: '',
    total: 0
  }
  query();
}

// 3. 查询用户列表（保持不变）
let query = () => {
  userListLoading.value = true;
  if (searchTime.value[0] !== '') {
    queryParams.value.start = formatDay(searchTime.value[0])
    queryParams.value.end = formatDay(searchTime.value[1])
  }
  api.get("/admin/user/page", queryParams.value).then(result => {
    userList.value = result.data.list || [];
    queryParams.value.total = result.total || result.data.total || 0;
  }).finally(() => {
    userListLoading.value = false;
  })
}

// 4. 状态开关修改（保持不变）
let switchHandler = (row) => {
  ElMessageBox.confirm(`是否修改用户[${row.nickname}]的状态？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const oldStatus = row.status;
    row.status = row.status === 1 ? 0 : 1;
    api.postJson("/admin/user/updateStatus", {id: row.id, status: row.status}).then(res => {
      if (res.code === 200) ElMessage.success("状态修改成功");
    }).catch(() => {
      ElMessage.error("状态修改失败");
      row.status = oldStatus;
    })
  }).catch(() => {
    ElMessage.info('已取消修改');
  })
}

// 5. 编辑表单相关变量（保持不变）
let editFormVisible = ref(false)
let editForm = ref({ // 表单初始值：密码为空，状态默认正常
  status: "1",
  userRoleId: undefined,
  password: ''
})
let editTitle = ref('编辑')

// 6. 打开新增弹窗（保持不变）
let addPage = () => {
  editFormVisible.value = true
  isAdd.value = true; // 新增时isAdd为true
  editTitle.value = "新增用户"
  reset() // 重置表单数据
}

// 7. 表单校验规则（核心修改：密码改为非必填）
let editFormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  nickname: [
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  phone: [
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
  ],
  password: [
    {
      required: false,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 12,
      message: '长度在 3 到 12 个字符',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 空值直接通过（无论新增还是修改）
        if (!value) return callback();
        // 有值时检查长度
        if (value.length >= 3 && value.length <= 12) return callback();
        return callback(new Error('长度在 3 到 12 个字符'));
      }
    }
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ],
  userRoleId: [
    {required: true, message: '请选择角色', trigger: 'change'}
  ]
}

// 8. 打开编辑弹窗（保持不变）
let edit = (row) => {
  editFormVisible.value = true
  isAdd.value = false; // 编辑时isAdd为false
  editTitle.value = "编辑用户"

  // 回显用户数据，密码置空（避免显示加密值）
  editForm.value = {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    phone: row.phone,
    email: row.email,
    status: String(row.status),
    remark: row.remark || '',
    userRoleId: row.userRoleId ? String(row.userRoleId) :
        (row.roleId ? String(row.roleId) :
            (row.role ? String(row.role.id) : undefined)),
    password: ''
  };
}

// 9. 关闭弹窗（保持不变）
function cancel() {
  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
  reset();
  editFormVisible.value = false;
}

// 10. 重置表单数据（保持不变）
function reset() {
  editForm.value = {
    id: '',
    username: '',
    nickname: '',
    phone: '',
    email: '',
    status: "1",
    password: '', // 始终空值
    remark: '',
    userRoleId: undefined
  }
}

// 11. 保存表单（保持不变）
function save() {
  editFormRef.value.validate((isValid) => {
    if (!isValid) return;
    const form = {...editForm.value};
    // 清除无用字段
    delete form.loginTime;
    delete form.regTime;
    delete form.role;
    // 新增时删除id
    if (isAdd.value) delete form.id;
    // 空密码不传递（无论新增还是修改）
    if (!form.password) delete form.password;

    api.postJson("/admin/user/save/update", form).then(result => {
      if (result.code === 200) {
        ElMessage.success(isAdd.value ? "添加成功" : "修改成功");
        query();
        cancel();
      } else {
        ElMessage.error(result.msg)
      }
    })
  });
}

// 12. 表格多选事件（保持不变）
const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};

// 13. 批量删除（保持不变）
const deleteSelectedRows = () => {
  const idsArray = selectedRows.value.map(row => row.id);
  if (idsArray.length === 0) return ElMessage.warning("请选择要删除的用户");

  ElMessageBox.confirm(`是否确认删除用户编号为[${idsArray.join(',')}]的数据?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = idsArray.join(',');
    api.delete(`/admin/user/del/${ids}`).then(result => {
      ElMessage.success("删除成功");
      query();
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};

// 14. 单个删除（保持不变）
let deleteOne = (row) => {
  ElMessageBox.confirm(`是否确认删除用户编号为[${row.id}]的数据?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.delete(`/admin/user/del/${row.id}`).then(result => {
      ElMessage.success("删除成功");
      query();
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 15. 获取角色列表（保持不变）
let roleList = ref([])
let roleListLoading = ref(false)
function queryRoleList() {
  roleListLoading.value = true
  return api.get("/role/all").then(result => {
    if (result.code === 200) {
      roleList.value = (result.data || []).map(item => ({
        userRoleId: String(item.id),
        roleName: item.roleName
      }))
    } else {
      ElMessage.error(result.msg || "获取角色列表失败")
    }
  }).catch(err => {
    ElMessage.error("获取角色列表失败")
    console.error("角色接口错误：", err)
  }).finally(() => {
    roleListLoading.value = false
  })
}

// 16. 批量重置密码（保持不变）
function resetPassword() {
  const idsArray = selectedRows.value.map(row => row.id);
  if (idsArray.length === 0) return ElMessage.warning("请选择要重置密码的用户");

  ElMessageBox.confirm(`是否为ID为[${idsArray.join(',')}]的用户重置密码为[123456]?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = idsArray.join(',');
    api.postJson("/admin/user/resetPassword", {ids}).then(res => {
      if (res.code === 200) {
        ElMessage.success("密码重置成功");
        query();
      }
    })
  })
}

// 17. 页面挂载时初始化（保持不变）
onMounted(async () => {
  await queryRoleList();
  resetQueryForm();
})
</script>

<template>
  <div class="app-container">
    <!-- 1. 查询表单区域（保持不变） -->
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" ref="queryFormRef">
        <el-form-item label="ID/昵称/用户名">
          <el-input v-model="queryParams.name" placeholder="输入ID/昵称/用户名" clearable/>
        </el-form-item>
        <el-form-item label="手机号/邮箱">
          <el-input v-model="queryParams.phone" placeholder="输入手机号/邮箱" clearable/>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
              v-model="queryParams.userRoleId"
              placeholder="请选择角色"
              maxlength="30"
              clearable
          >
            <el-option v-if="roleList.length === 0" label="暂无角色数据" value="" disabled/>
            <el-option
                v-else
                v-for="role in roleList"
                :key="role.userRoleId"
                :label="role.roleName"
                :value="role.userRoleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="queryParams.type"
              placeholder="选择状态"
              clearable
          >
            <el-option label="封停" value="0"/>
            <el-option label="正常" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="searchTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 2. 功能按钮区域（保持不变） -->
    <el-row class="mb-2">
      <el-col>
        <el-button type="success" :icon="Plus" plain @click="addPage">新增</el-button>
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow">删除</el-button>
        <el-button type="warning" :icon="Clock" plain @click="resetPassword" :disabled="!isSelectRow">重置密码</el-button>
      </el-col>
    </el-row>

    <!-- 3. 用户列表表格（保持不变） -->
    <el-row>
      <el-table
          :data="userList"
          border
          stripe
          @selection-change="handleSelectionChange"
          v-loading="userListLoading"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="username" label="用户名" width="180"/>
        <el-table-column prop="nickname" label="昵称" width="180"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="email" label="邮箱" width="220"/>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-switch
                :model-value="scope.row.status"
                inline-prompt
                :active-value="1"
                active-text="正常"
                :inactive-value="0"
                inactive-text="停用"
                class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="switchHandler(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">{{ formatDay(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="最后登录时间" width="180">
          <template #default="scope">{{ formatLoginTime(scope.row.lastLoginTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="deleteOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 4. 分页控件（保持不变） -->
    <el-row class="mt-2">
      <el-col :span="24" class="text-right">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>

    <!-- 5. 新增/编辑弹窗（调整密码提示） -->
    <el-dialog v-model="editFormVisible" :title="editTitle" width="600px" append-to-body>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <!-- 用户名 + 密码行（调整密码提示） -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" placeholder="请输入用户名" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                  v-model="editForm.password"
                  placeholder="可选,新增默认为123456"
              maxlength="30"
              show-password
              />

            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他表单行（保持不变） -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="手机号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" placeholder="邮箱" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="editForm.nickname" placeholder="请输入用户昵称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="editForm.status">
                <el-radio-button label="1">正常</el-radio-button>
                <el-radio-button label="0">关闭</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-input v-model="editForm.position" placeholder="岗位" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="userRoleId">
              <el-select
                  v-model="editForm.userRoleId"
                  placeholder="请选择角色"
                  maxlength="30"
                  filterable
                  clearable
                  :loading="roleListLoading"
              >
                <el-option v-if="roleListLoading" label="加载中..." value="" disabled/>
                <el-option v-else-if="roleList.length === 0" label="暂无角色数据" value="" disabled/>
                <el-option
                    v-else
                    v-for="role in roleList"
                    :key="role.userRoleId"
                    :label="role.roleName"
                    :value="role.userRoleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="editForm.remark" type="textarea" placeholder="备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹窗底部按钮（保持不变） -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.mb-2 { margin-bottom: 8px; }
.mt-2 { margin-top: 8px; }
.text-xs { font-size: 12px; }
.text-gray-500 { color: #666; }
</style>